package com.apes.fn.business.fixedLoss.repository;

import com.apes.fn.business.fixedLoss.modle.LossQuotation;
import com.apes.fn.business.fixedLoss.modle.LossQuotationItem;
import com.apes.fn.business.fixedLoss.modle.LossQuotationPlan;
import com.apes.fn.server.productRequire.ProductRequire;
import com.apes.framework.jpa.repository.CustomRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

/**
 * @ClassName : LossQuotationRepository
 * @Description : 定损报价单
 * @Author : WSJ
 * @Date: 2020-03-07 14:29
 */
public interface LossQuotationRepository extends CustomRepository<LossQuotation,String> {
    /**
     * 查询是否存在该报案单对应的未完成定损报价单
     * @param  carAccident 车险报案单
     * @return
     */
    @Query("select a from LossQuotation a where a.carAccident = :carAccident and a.state not in ('repeal')" +
            "and not exists (select b from RetailOrder b where b.source = a.id )")
    List<LossQuotation> findByCarAccident(@Param("carAccident") String carAccident);

    /**
     * 删除确认方案服务单号为空
     * @param
     * @return
     */
    @Query("delete  from LossQuotationPlan a where a.servicePlan is null")
    int deleteByServicePlan();

    /**
     * 查询是否存在该报案单对应的未完成定损报价单
     *
     * @return
     */
    @Query(value = "select b from LossQuotation a , LossQuotationPlan  b where a.id = b.lossQuotation and  a.carAccident = :carAccident and a.state not in ('repeal')")
    List<LossQuotationPlan> findPlanByCarAccident(@Param("carAccident") String carAccident);

    /**
     * 查询该报案单是否有未完成的相关要货单
     *
     * @return
     */
    @Query("select b from ProductRequire b  where b.state in ('create','approve') " +
            " and b.source = :lossQuotationId")
    List<ProductRequire> findProductRequireForID(@Param("lossQuotationId") String ID);

    /**
     * 查询该定损单是否有已转服务的定损报价明细
     *
     * @return
     */
    @Query("select b from LossQuotationItem b,LossQuotation a " +
            " where a.id = b.lossQuotation and b.servicePlan is not null and a.id = :lossQuotationId ")
    List<LossQuotationItem> findLossQuotationItemForID(@Param("lossQuotationId") String ID);

    @Query("SELECT T FROM LossQuotation T LEFT JOIN CarAccident C ON T.carAccident = C.id WHERE T.id IN (:ids) AND C.businessStaff IS NOT NULL ")
    List<LossQuotationPlan> findLossQuotationByIds(@Param("ids") List ids);

    @Query("SELECT T FROM LossQuotation T WHERE T.customerExpand.id = :customerExpandId and T.state Not IN :states")
    List<LossQuotation> findCustomerExpandAndStateNotIn(String customerExpandId,List<String> states);

}
